package com.util.common;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/1/13 0013.
 */
public class ValidateHelper {
    public ValidateHelper() {
    }

    public static boolean isPhone(String phone) {
        String matcher = "^[1][3,4,5,7,8][0-9]{9}$";
        boolean flag = Pattern.matches(matcher, phone);
        return flag;
    }

    public static boolean isEmail(String email) {
        String matcher = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        return Pattern.matches(matcher, email);
    }

    public static Map convertErrorToMap(ObjectError error) {
        HashMap map = new HashMap();
        map.put("object", error.getObjectName());
        map.put("message", error.getDefaultMessage());
        if(error instanceof FieldError) {
            map.put("field", ((FieldError)error).getField());
        }

        return map;
    }

    public static String firstErrorMessage(BindingResult result) {
        return result.hasErrors()?((ObjectError)result.getAllErrors().get(0)).getDefaultMessage():null;
    }
}
